from django import template
from django.contrib.contenttypes.models import ContentType
from ..models import Comment
from comment.forms.comment import CommentForm
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage, InvalidPage


register = template.Library()


@register.simple_tag
def get_comment_count(obj):
    content_type = ContentType.objects.get_for_model(obj)
    return Comment.objects.filter(content_type=content_type, object_id=obj.pk).count()


@register.simple_tag
def get_comment_form(obj):
    content_type = ContentType.objects.get_for_model(obj)
    comment_form = CommentForm(initial={
        'content_type': content_type.model,
        'object_id': obj.pk,
        'parent_comment_id': 0,
    })

    return comment_form


@register.simple_tag
def get_comment_list(request, obj):
    content_type = ContentType.objects.get_for_model(obj)
    comments = Comment.objects.filter(content_type=content_type, object_id=obj.pk).all()

    paginator = Paginator(comments, 10)
    page = request.GET.get('page')
    try:
        comments = paginator.page(page)
    except PageNotAnInteger:
        comments = paginator.page(1)
    except(EmptyPage, InvalidPage):
        comments = paginator.page(paginator.num_pages)


    # return comments.order_by('-create_datetime')  # 这里不需要排序
    return comments

